import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Button, DatePicker, Table, Popconfirm, Avatar, Modal } from 'antd';
import Img from 'react-image';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import ShowUserInfo from './ShowUserInfo';
import styles from './UserManagement.less';
import globalConstant from '../../utils/globalConstant';

const FormItem = Form.Item;


@connect(({ userManage, loading }) => ({
  userManage,
  loading: loading.models.userManage,
}))
@Form.create()
export default class UserManagement extends PureComponent {
  state = {
    showUserInfoVisible: false,
    id: undefined,
    pageNum: globalConstant.paging.defaultPageNum,
    pageSize: globalConstant.paging.defaultPageSize,
    form: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
  }
  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.state.form,
    };
    this.setState({
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    });
    dispatch({
      type: 'userManage/fetch',
      payload: params,
    });
  }
  handleModalInfo = (flag) => {
    this.setState({
      showUserInfoVisible: !!flag,
    });
  }
  handleModalInfoOkButton = (flag) => {
    this.setState({
      showUserInfoVisible: !!flag,
    });
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'userManage/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
  }
  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const rangeValue = fieldsValue.date || undefined;
      console.log(fieldsValue);
      dispatch({
        type: 'userManage/fetch',
        payload: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.select || null,
          keywordsValue: fieldsValue.keywordsValue || null,
        },
      });
      this.setState({
        form: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.select || null,
          keywordsValue: fieldsValue.keywordsValue || null,
        },
      });
    });
  }
  showInfo = (value, flag) => {
    this.setState({
      showUserInfoVisible: !!flag,
      // 先屏蔽,等待正式数据
      id: value.id,
    });
  };
  checkUser = (id, status) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/updateStatus',
      payload: {
        id,
        isAuthed: !status,
      },
      callback: () => {
        dispatch({
          type: 'userManage/fetch',
          payload: {
            pageNum: this.state.pageNum,
            pageSize: this.state.pageSize,
          },
        });
      },
    });
  };
  showPictureModal = (values) => {
    console.log(values);
    Modal.info({
      title: '身份证图片',
      content: (
        values === null ? '暂无图片' : (
          <Img style={{ width: (243), height: (153) }} src={values} />
        )
      ),
      maskClosable: true,
      onOk() {},
    });
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字">
              {getFieldDecorator('keywordsValue')(
                <Input placeholder="请输入搜索关键字" />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="关键字类型">
              {getFieldDecorator('select')(
                <Select
                  mode="multiple"
                >
                  <Select.Option value="loginName">用户名</Select.Option>
                  <Select.Option value="userAddress">居住地址</Select.Option>
                  <Select.Option value="userMobile">手机</Select.Option>
                  <Select.Option value="userIdcard">身份证号</Select.Option>
                  <Select.Option value="userName">姓名</Select.Option>
                  <Select.Option value="userEmail">邮箱</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="创建日期">
              {getFieldDecorator('date')(
                <DatePicker.RangePicker
                  style={{ width: '100%' }}
                  format={globalConstant.dateFormat}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24} >
          <Col span={24} style={{ textAlign: 'right' }}>
            <span className={styles.submitButtons}>
              <Button icon="search" type="primary" htmlType="submit" >查询</Button>
              <Button icon="reload" style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    const { loading, userManage: { userList } } = this.props;
    const { showUserInfoVisible, id } = this.state;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: userList && userList.totals,
      ...globalConstant.pagingFormat,
    };
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
      },
      {
        title: '姓名',
        dataIndex: 'userName',
      },
      {
        title: '身份证号码',
        dataIndex: 'userIdcard',
      },
      {
        title: '手机号码',
        dataIndex: 'userMobile',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        render: (text) => {
          console.log(text)
          return moment(text).format('YYYY-MM-DD');
        },
      },
      {
        title: '身份证正面',
        dataIndex: 'idcardPhotoFront',
        render: text => (
          <Avatar shape="square" src={text} size="large" onClick={() => this.showPictureModal(text)} />
        ),
      },
      {
        title: '身份证反面',
        dataIndex: 'idcardPhotoSide',
        render: text => (
          <Avatar shape="square" src={text} size="large" onClick={() => this.showPictureModal(text)} />
        ),
      },
      {
        title: '账号状态',
        render: (text) => {
          return (
            <Popconfirm title="是否确定审核通过？" onConfirm={() => { this.checkUser(text.id, text.isAuthed); }}>
              <Button type={text.isAuthed ? 'danger' : 'primary'} >{text.isAuthed ? '已审核' : '未审核' }</Button>
            </Popconfirm>
          );
        },
      },
      {
        title: '操作',
        key: 'key',
        render: (text) => {
          return (
            <Button onClick={() => { this.showInfo(text, true); }} style={{ marginLeft: 10 }} >
              查看详情
            </Button>
          );
        },
      },
    ];
    return (
      <PageHeaderLayout title="用户管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
          </div>
        </Card>
        <Card bordered>
          <Table
            bordered
            loading={loading}
            rowKey={record => record.id}
            dataSource={userList && userList.items}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <Modal
          title="用户详情"
          visible={showUserInfoVisible}
          width="60%"
          onOk={() => this.handleModalInfoOkButton()}
          onCancel={() => this.handleModalInfo()}
          footer={null}
          destroyOnClose
        >
          <ShowUserInfo data={id} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
